package com.leyou.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.bo.SpuBo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.pojo.PageResult;
import com.leyou.mapper.*;
import com.leyou.pojo.*;
import com.leyou.service.CategoryService;
import com.leyou.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<SpuBo> querySpuByPageAndSort(Integer page, Integer rows, String key, Boolean saleable) {
        // 1、查询SPU
        // 开启分页，最多允许查询100条
        PageHelper.startPage(page, Math.min(rows, 100));
        // 过滤条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 上下架
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        // 模糊查询
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }
        // 默认排序
        example.setOrderByClause("last_update_time desc");
        // 查询
        List<Spu> spus = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(spus)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 2、封装业务对象SpuBo
        List<SpuBo> collect = spus.stream().map(spu -> {
            SpuBo spuBo = new SpuBo();
            // 属性拷贝
            BeanUtils.copyProperties(spu, spuBo);
            // 解析商品分类名称
            List<String> strings = categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            // 将商品分类名称拼接后存入
            spuBo.setCname(StringUtils.join(strings, "/"));
            // 解析品牌名称
            Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
            spuBo.setBname(brand.getName());
            return spuBo;
        }).collect(Collectors.toList());
        PageInfo<Spu> info = new PageInfo<>(spus);
        return new PageResult<>(info.getTotal(), collect);
    }

    @Transactional
    public void save(SpuBo spuBo) {
        // 新增spu
        // 设置默认属性
        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());
        int count = spuMapper.insertSelective(spuBo);
        if (count != 1) {
            throw new LyException(ExceptionEnum.GOODS_SAVE_ERROR);
        }
        // 新增spuDetail
        SpuDetail spuDetail = spuBo.getSpuDetail();
        spuDetail.setSpuId(spuBo.getId());
        spuDetailMapper.insertSelective(spuDetail);
        // 保存sku和库存
        saveSkuAndStock(spuBo);
    }

    @Transactional
    public void updateGoods(SpuBo spuBo) {
        // 先删除sku和库存信息
        deleteSkuAndStock(spuBo.getId());
        // 保存sku和库存
        saveSkuAndStock(spuBo);
        // 更新spu
        spuBo.setLastUpdateTime(new Date());
        spuBo.setCreateTime(null);
        spuBo.setValid(null);
        spuBo.setSaleable(null);
        spuMapper.updateByPrimaryKeySelective(spuBo);
        // 更新spu详情
        spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());
    }

    /**
     * 保存tb_sku和tb_stock
     *
     * @param spuBo
     */
    private void saveSkuAndStock(SpuBo spuBo) {
        List<Stock> stocks = new ArrayList<>();
        spuBo.getSkus().forEach(sku -> {
            // 新增sku
            sku.setSpuId(spuBo.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insertSelective(sku);
            // 新增库存
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            stocks.add(stock);
        });
        stockMapper.insertList(stocks);
    }

    public List<Sku> querySkusBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skus = skuMapper.select(sku);
        // 通过sku_id查询库存
        skus.forEach(s -> {
            Stock stock = stockMapper.selectByPrimaryKey(s.getId());
            s.setStock(stock.getStock());
        });
        return skus;
    }

    public SpuDetail querySpuDetailBySpuId(Long spuId) {
        return spuDetailMapper.selectByPrimaryKey(spuId);
    }

    @Transactional
    public void deleteGoods(Long spuId) {
        // 先删除sku和库存信息
        deleteSkuAndStock(spuId);
        // 再删除spu和spu_detail
        spuMapper.deleteByPrimaryKey(spuId);
        spuDetailMapper.deleteByPrimaryKey(spuId);
    }

    /**
     * 通过spu_id删除tb_sku
     * 通过sku_id删除tb_stock
     *
     * @param spuId
     */
    private void deleteSkuAndStock(Long spuId) {
        // 通过spu_id查询sku
        Sku querySku = new Sku();
        querySku.setSpuId(spuId);
        List<Sku> skus = skuMapper.select(querySku);
        // 删除sku
        if (!CollectionUtils.isEmpty(skus)) {
            // 获得sku_id集合
            List<Long> ids = skus.stream().map(sku -> sku.getId()).collect(Collectors.toList());
            // 通过sku_id删除tb_stock
            Example example = new Example(Stock.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("skuId", ids);
            stockMapper.deleteByExample(example);
            // 删除sku
            skuMapper.delete(querySku);
        }
    }

    public void changeSaleable(Long spuId) {
        // 先查后更新
        Spu dbSpu = this.spuMapper.selectByPrimaryKey(spuId);
        if (null != dbSpu) {
            dbSpu.setSaleable(!dbSpu.getSaleable());
            this.spuMapper.updateByPrimaryKey(dbSpu);
        }
    }

    public Spu querySpuById(Long id) {
        return this.spuMapper.selectByPrimaryKey(id);
    }

    public Sku querySkuById(Long id) {
        return this.skuMapper.selectByPrimaryKey(id);
    }

}
